// pages/types/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

const app = getApp()
const cacheDateKey = 'today_is_login'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLogin: null,
        tipDialog: false,
        tipMsg: '',
        text: '',
        theme: '',
        loginsrc: '',
        huaweilogin: '',
        searchText: '', // 搜索关键词  
        options: [], // 下拉框原始选项  
        filteredOptions: [], // 根据搜索关键词过滤后的选项  
        showDropdown: false, // 控制下拉框的显示与隐藏  
        searchText: '',
        ids: [],
        cid1: [],
        cid3: [],
        title: [],
        // 中医诊断及体检,是否显示子菜单
        show: false,
        // 其他体验, 控制遮罩层
        otherShow: false
    },
    handleInput: function (e) {
        let searchText = e.detail.value;
        var reqUri = app.globalData.domain + 'v4/index/searchQuestion';
        let that = this;
        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                keyword: searchText,
            },
            success(res) {
                if (res.data.code == 0) {
                    that.setData({
                        searchText,
                        filteredOptions: res.data.data,
                        showDropdown: searchText.trim().length > 0,
                    });
                    wx.setStorageSync('searchText', searchText);
                }

            }
        })
    },
    handleDropdownItemTap: function (e) {
        let value = e.currentTarget.dataset.value;
        let id = e.currentTarget.dataset.id;
        let cid1 = e.currentTarget.dataset.cid1;
        let cid3 = e.currentTarget.dataset.cid3;
        this.setData({
            searchText: wx.getStorageSync('searchText'), // 设置搜索文本为选中的值  
            showDropdown: false, // 隐藏下拉框  
        });
        // 执行其他逻辑，比如页面跳转等  
        wx.navigateTo({
            url: '/pages/newDetail/indexV2?type=' + cid1 + '&cid3=' + cid3 + '&qid=' + id,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var curDate = new Date();
        var curDateDetail = curDate.getFullYear() + '-' + curDate.getMonth() + '-' + curDate.getDate();
        var cacheDate = wx.getStorageSync(cacheDateKey);
        var cacheUserInfo = wx.getStorageSync('user_phone');
        var isChooseProtocal = wx.getStorageSync('isChooseProtocal') ? wx.getStorageSync('isChooseProtocal') : false;
        //变量赋值
        this.setData({
            isChooseProtocal: isChooseProtocal,
        });
        this.gettext();
        if (!cacheDate || cacheDate != curDateDetail) {
            wx.setStorageSync(cacheDateKey, curDateDetail);
            wx.request({
                url: app.globalData.domain + 'index/index/logUserIp',
                data: {
                    'user_phone': cacheUserInfo.purePhoneNumber,
                },
                success: function (res) {

                }
            });

        }
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        // 如果进入首页, 带有体质查询赠送卡的标志. 
        if (options.tizhiPresent == 1) {
            this.isShowFree();
        }
    },
    isShowFree: function () {
        wx.request({
            url: app.globalData.domain + 'v5/index/tizhiPresent?agentFree=1',
            data: {},
            success(res) {
                console.log('tizhiPresent:' + res.data.data)
                if (res.data.code == 0) {
                    const startTime = res.data.data.start;
                    const endTime = res.data.data.end;
                    const nowInSeconds = Math.floor(Date.now() / 1000);
                    wx.setStorageSync('tizhiPresent', 1); 
                    // 当前用户是否已经用过. 200代表可以使用体验日卡
                    if (res.data.data.is_used == 200) {
                        wx.setStorageSync('used_day', 200);
                    } else {
                        // 不能使用的情况, 要更改
                        wx.setStorageSync('used_day', 0);
                    }
                }
            }
        })
    },    
    onShareAppMessage() {
        return {
            title: '天纪云',
            path: '/pages/menu/index'
        }
    },
    onShareTimeline() {
        return {
            title: '天纪云'
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (wx.getStorageSync('theme') == 'style1') {
            this.setData({
                theme: 'style1',
                loginsrc: 'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png',
                huaweilogin: 'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png',
                wode: '/images/wodepng.png',
                indexpng: '/images/indexpng.png',
                gypng: '/images/gypng.png'
            })
        } else {
            this.setData({
                theme: 'init',
                loginsrc: 'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png',
                huaweilogin: 'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png',
                wode: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/tab_me_n@2x.png',
                indexpng: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/tab_home_s@2x.png',
                gypng: '/images/ai.png'
            })
        }
        this.setData({
            isLogin: wx.getStorageSync('isLogin')
        })

        setTimeout(() => {
            app.show(this, 'show', 1)
        }, 1000);
    },
    getPhoneNumber(e) {
        console.log(e);
        console.log(this.isLogin);
        console.log(wx.getStorageSync('isLogin'));
        let {
            encryptedData,
            iv,
            code
        } = e.detail
        // 如果授权获取手机号则进入下个页面 
        if (code) {
            this.getPhone(code)
        } else {
            Dialog.alert({
                title: '温馨提示',
                message: '请授权登录',
                theme: 'round-button',
            }).then(() => {
                // on close
            });
        }
    },

    // 用户获取手机号
    getPhone(code) {
        let that = this
        var reqUri = app.globalData.domain + 'index/index/getUserWxPhone';
        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                code,
            },
            success(res) {
                console.log(res)
                if (res.data.code == app.globalData.successCode) {
                    let {
                        phoneNumber
                    } = res.data.data
                    // 将用户的 手机号缓存
                    wx.setStorageSync('user_phone', res.data.data)
                    that.login(phoneNumber)
                } else {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
            }
        })
    },

    // 用户登录
    login(phone) {
        let that = this
        var reqUri = app.globalData.domain + 'index/index/doReg';
        let uid = wx.getStorageSync('toid') ?? 0;
        let cid3 = wx.getStorageSync('tocid3');
        
        if (!cid3 || cid3 == undefined) cid3 = that.data.cid3;

        wx.request({
            url: reqUri,
            method: 'POST',
            data: {
                phone,
                types: 'mini',
                openid: app.globalData.openId,
                uid: uid,
                cid3: cid3,
                agentId: wx.getStorageSync('agentId') ?? 1
            },
            success(res) {
                console.log(res)
                if (res.data.code == app.globalData.successCode) {
                    Toast.success('登录成功,即将跳转')
                    wx.setStorageSync('isLogin', true)
                    wx.redirectTo({
                        url: '/pages/personal/me',
                    })
                } else {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg
                    })
                    return;
                }
            }
        })
    },
    gettext() {
        let that = this;
        wx.request({
            url: app.globalData.domain + 'v4/index/gettext',
            success(res) {
                if (res.data.code == 0) {
                    console.log(res.data)
                    that.setData({
                        banner: res.data.banner,
                        data6: res.data.data6
                    });

                }
            }
        })
    },

    onHide: function () {
        setTimeout(() => {
            app.show(this, 'show', 0)
        }, 1000);
    },

    toDetail(e) {
        let {
            type
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: '/pages/newDetail/index?type=' + type,
        })
    },
    /**
     * 至首页
     */
    toLogin() {
        wx.redirectTo({
            url: '/pages/login/index',
        })
    },
    /**
     * 至个人中心
     */
    toMe() {
        wx.navigateTo({
            url: '/pages/personal/me',
        })
    },
    toCertificate: function () {
        wx.navigateTo({
            url: '/pages/personal/certificate',
        })
    },
    /**
     * 至个人中心
     */
    toGroupMenu() {
        wx.navigateTo({
            url: '/pages/menu/group',
        })
    },
    /**
     * 至个人中心
     */
    toPersonalMenu() {
        wx.navigateTo({
            url: '/pages/menu/personal',
        })
    },
    peeling() {
        console.log(wx.getStorageSync('theme'));
        if (wx.getStorageSync('theme') == 'style1') {
            app.globalData.theme = 'init'
            wx.setStorageSync('theme', 'init');
            this.setData({
                theme: 'init',
                loginsrc: 'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png',
                huaweilogin: 'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png',
                wode: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/tab_me_n@2x.png',
                indexpng: 'https://aiw.oss-cn-beijing.aliyuncs.com/v3/tab_home_s@2x.png',
                gypng: '/images/ai.png'
            })
        } else {
            app.globalData.theme = 'style1'
            wx.setStorageSync('theme', 'style1');

            this.setData({
                theme: 'style1',
                loginsrc: 'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png',
                huaweilogin: 'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png',
                wode: '/images/wodepng.png',
                indexpng: '/images/indexpng.png',
                gypng: '/images/gypng.png'
            })
        }
        console.log(wx.getStorageSync('theme'));
        console.log(this.data.theme);
    },
    //点击事件  
    toImg0: function (e) {
        var img = e.currentTarget.dataset.img;
        wx.previewImage({
            urls: [img], //需要预览的图片http链接列表，注意是数组
            current: '', // 当前显示图片的http链接，默认是第一个
            success: function (res) {},
            fail: function (res) {},
            complete: function (res) {},
        })
    },
    toImg1: function (e) {
        var img = e.currentTarget.dataset.img;
        wx.previewImage({
            urls: [img], //需要预览的图片http链接列表，注意是数组
            current: '', // 当前显示图片的http链接，默认是第一个
            success: function (res) {},
            fail: function (res) {},
            complete: function (res) {},
        })
    },
    toImg2: function (e) {
        var img = e.currentTarget.dataset.img;
        wx.previewImage({
            urls: [img], //需要预览的图片http链接列表，注意是数组
            current: '', // 当前显示图片的http链接，默认是第一个
            success: function (res) {},
            fail: function (res) {},
            complete: function (res) {},
        })
    },
    toImg3: function (e) {
        var img = e.currentTarget.dataset.img;
        wx.previewImage({
            urls: [img], //需要预览的图片http链接列表，注意是数组
            current: '', // 当前显示图片的http链接，默认是第一个
            success: function (res) {},
            fail: function (res) {},
            complete: function (res) {},
        })
    },
    toImg4: function (e) {
        var img = e.currentTarget.dataset.img;
        wx.previewImage({
            urls: [img], //需要预览的图片http链接列表，注意是数组
            current: '', // 当前显示图片的http链接，默认是第一个
            success: function (res) {},
            fail: function (res) {},
            complete: function (res) {},
        })
    },
    // 体质查询
    physicalSearch: function () {
        wx.navigateTo({
            url: '/pages/phySearch/index',
        })
    },
    // 中医诊断
    toMedical() {
        wx.navigateTo({
            url: '/pages/newDetail/indexV2?type=1-1-5&cid3=19'
        })
    },
    // 中医诊断&体检. TODO: 代码可以抽取
    onClickShow() {
        this.setData({
            show: true
        });
    },
    onClickHide() {
        this.setData({
            show: false
        });
    },
    // 其他体验, 控制. otherShow
    onOtherShow() {
        this.setData({
            otherShow: true
        });
    },
    otherShowHide() {
        this.setData({
            otherShow: false
        });
    },
    // 症状查询
    searchSymptom() {
        wx.navigateTo({
            url: '/pages/symptoms/index'
        })
    }
})